const  tools = require("./tools");
const  db = require("./db");
const  {upPic} = require("./upPic");
const mongodb = require("mongodb")
//添加店铺接口
module.exports.addShopList=async function(req,res){
    const{ok,params} = await upPic(req,"shopPic");
    if(ok===1){
        const shopType = await db.findOneById("shopTypeList",params.shopTypeId);
        await db.insertOne("shopList",{
            createTime:Date.now(),
            shopName:params.shopName,
            isTop:params.isTop === "true",
            shopPic:params.newPicName,
            shopTypeName:shopType.shopTypeName,
            shopTypeId:shopType._id
        })
        tools.json(res,1,"插入成功")
    }else{
        tools.json(res);
    }
}
//获取店铺列表
module.exports.getShopList=async function(req,res){
    let pageIndex = req.query.pageIndex/1;
    let pageSum = 1;
    let limit = 5;
    let whereObj = {};
    //判断如果传进来id的haul就俺id查询
    if(req.query.shopTypeId.length>0)
        whereObj.shopTypeId = mongodb.ObjectId(req.query.shopTypeId);
    const count = await db.count("shopList",whereObj);
    pageSum = Math.ceil(count/limit);
    if(pageSum < 1)
        pageSum = 1;
    if(pageIndex >pageSum)
        pageIndex = pageSum;
    if(pageIndex < 1)
        pageIndex = 1;
    const shopList = await db.find("shopList",{
        whereObj,
        sortObj:{cetateTime:-1},
        skip:(pageIndex-1)*limit,
        limit
    });

    res.json({
        ok:1,
        shopList,
        pageIndex,
        pageSum
    })
}

//通过id获取你想要添加商品类别的店铺类别和店铺信息
module.exports.getShopListById = async function(req,res){
    // console.log(req.query)
    // const shopId = mongodb.ObjectId(req.query.shopId)
    const shopId = req.query.id
    // console.log(shopId)
    const shopList = await db.findOneById("shopList",shopId)
    // console.log(shopList)
    res.json({
        ok:1,
        shopList
    })
}